#include "../include/vds.h"
#define BUFFER_SIZE 1024
#define PATH_SIZE 256
int verify_path(MYSQL *conn,const char *username,const char *path){
    char sql[BUFFER_SIZE];
    MYSQL_RES *res;
    MYSQL_ROW row;
    char new_path[PATH_SIZE];
    char filename[PATH_SIZE];
    if (split_path(path, new_path, filename) == -1) {
        return -1;
    }
    snprintf(sql,sizeof(sql),"select count(*) from user_files where user_id = (select id from user where username ='%s') and path = '%s'and filename = '%s';", username, new_path, filename);
    if(mysql_query(conn,sql)!=0){
        return -1;
    }

    res = mysql_store_result(conn);
    if(res == NULL){
        return -1;
    }

    row = mysql_fetch_row(res);
    int count = atoi(row[0]);
    mysql_free_result(res);

    return count > 0 ? 0 : -1;
}

int split_path(const char *path, char *new_path, char *filename) {
    if (path == NULL || new_path == NULL || filename == NULL) {
        return -1;
    }
    const char *last_slash = strrchr(path, '/');

    if (last_slash == NULL) {
        // 如果路径中没有 /，则整个路径为文件名，新路径为空
        strcpy(new_path, "");
        strcpy(filename, path);
    } else {
        // 复制新路径部分
        size_t path_length = last_slash - path;
        strncpy(new_path, path, path_length);
        new_path[path_length] = '\0';
        // 复制文件名部分
        strcpy(filename, last_slash + 1);
    }
    if (strlen(new_path) >= 0 && new_path[0] != '/') {
         memmove(new_path + 1, new_path, strlen(new_path) + 1);
         new_path[0] = '/';
    }

    return 0;
}

int cmd_cd(MYSQL *conn,const char * username, const char *path){
    if(strlen(path)==1&&path[0]=='/'){
        return 0;
    }
    if(verify_path(conn,username,path)!=0){
        return -1;
    }else{
        return 0;
    }
}

// 判断是否为文件夹类型
int is_folder(MYSQL *conn, const char *username, const char *path) {
    char new_path[PATH_SIZE];
    char filename[PATH_SIZE];
    char sql[BUFFER_SIZE];
    MYSQL_RES *res;
    MYSQL_ROW row;

    if (split_path(path, new_path, filename) == -1) {
        return -1;
    }
    snprintf(sql, sizeof(sql), "SELECT type FROM user_files WHERE user_id = (SELECT id FROM user WHERE username = '%s') AND path = '%s' AND filename = '%s';", username, new_path, filename);

    if (mysql_query(conn, sql) != 0) {
        return -1;
    }

    res = mysql_store_result(conn);
    if (res == NULL) {
        return -1;
    }

    row = mysql_fetch_row(res);
    if (row == NULL) {
        mysql_free_result(res);
        return -1;
    }

    int result = (strcmp(row[0], "d") == 0) ? 1 : 0;
    mysql_free_result(res);
    return result;
}

int cmd_ls(MYSQL *conn, const char *username, const char *path, char *output) {
    char sql[BUFFER_SIZE];
    MYSQL_RES *res;
    MYSQL_ROW row;
    if (strcmp(path, "/") == 0) {
        // 如果路径为根目录 '/'，直接查询所有相关子文件
        snprintf(sql, sizeof(sql), "SELECT filename FROM user_files WHERE user_id = (SELECT id FROM user WHERE username = '%s') AND path = '/';", username);
    } else {
        // 检查路径是否存在
        if (verify_path(conn, username, path) != 0) {
            return -1;
        }

        // 判断是文件还是文件夹
        if (is_folder(conn, username, path) == 0) {
            char filename[PATH_SIZE];
            char new_path[PATH_SIZE];
            split_path(path, new_path, filename);
            strcpy(output, filename);
            return 0;
        }

        snprintf(sql, sizeof(sql), "SELECT filename FROM user_files WHERE user_id = (select id from user where username = '%s') AND path ='%s';", username, path);
    }

    if (mysql_query(conn, sql) != 0) {
        return -1;
    }

    res = mysql_store_result(conn);
    if (res == NULL) {
        return -1;
    }

    output[0] = '\0';
    size_t row_num = mysql_num_rows(res);
    for (size_t i = 0; i < row_num; i++) {
        if (i != 0) {
            strcat(output, " ");
        }
        row = mysql_fetch_row(res);
        strcat(output, row[0]);
    }

    mysql_free_result(res);
    return 0;
}

int cmd_mkdir(MYSQL *conn,const char *username, const char *path){
    if(strlen(path)==1 && path[0] == '/'){
        return -1;
    }

    char sql[BUFFER_SIZE];
    char new_path[PATH_SIZE];
    char filename[PATH_SIZE];
    if (split_path(path, new_path, filename) == -1) {
        return -1;
    }

    // 检查父目录是否存在
    char parent_path[PATH_SIZE];
    strcpy(parent_path, new_path);
    if(strlen(new_path)==1&&new_path[0]=='/'){
        snprintf(sql,sizeof(sql),
                 "insert into user_files(user_id,file_id,type,path,filename) values ("
                 "(select id from user where username='%s'),"
                 "NULL,'d','/','%s');",username,filename);
        if (mysql_query(conn, sql) != 0) {
            return -1;
        }
        return 0;
    }
    if (verify_path(conn, username, parent_path) != 0) {
        return -1;
    }
    snprintf(sql,sizeof(sql),
             "insert into user_files(user_id,file_id,type,path,filename) values ("
             "(select id from user where username='%s'),"
             "NULL,'d','%s','%s');",username,new_path,filename);
    if (mysql_query(conn, sql) != 0) {
        return -1;
    }
    if (mysql_affected_rows(conn) != 1) {
        return -1;
    }
    return 0;
}

int is_folder_empty(MYSQL *conn, const char *username, const char *path) {
    char sql[BUFFER_SIZE];
    char check_path[PATH_SIZE];
    char new_path[PATH_SIZE];
    char filename[PATH_SIZE];

    if (split_path(path, new_path, filename) == -1) {
        return -1;
    }

    strcpy(check_path, path);
    if (check_path[strlen(check_path) - 1] != '/') {
        strcat(check_path, "/");
    }

    snprintf(sql, sizeof(sql), 
             "SELECT COUNT(*) FROM user_files "
             "WHERE user_id=(select id from user where username = '%s') AND (path = '%s' OR path LIKE '%s%%') AND filename != '%s';", username, path, check_path, filename);
    
    if (mysql_query(conn, sql) != 0) {
        fprintf(stderr, "Error querying folder content count: %s\n", mysql_error(conn));
        return -1;
    }
    
    MYSQL_RES *res = mysql_store_result(conn);
    if (res == NULL) {
        fprintf(stderr, "Error getting result for folder content count: %s\n", mysql_error(conn));
        return -1;
    }
    
    MYSQL_ROW row = mysql_fetch_row(res);
    int count = atoi(row[0]);
    mysql_free_result(res);

    return count == 0;
}


int cmd_rmdir(MYSQL *conn,const char *username, const char *path){
    if(strlen(path)==1 && path[0]=='/'){
        return -1;
    }
    char sql[BUFFER_SIZE];
    if (verify_path(conn, username, path) != 0) {
        return -1;
    }

    // 调用检查文件夹是否为空的函数
    if (!is_folder_empty(conn, username, path)) {
        printf("Folder is not empty, cannot delete.\n");
        return -1;
    }

    char new_path[PATH_SIZE];
    char filename[PATH_SIZE];
    if (split_path(path, new_path, filename) != 0) {
        return -1;
    }
    snprintf(sql,sizeof(sql),"delete from user_files where user_id = (select id from user where username='%s') and path = '%s' and filename='%s';",username,new_path,filename);
    if(mysql_query(conn,sql)==-1){
        return -1;
    }
    if (mysql_affected_rows(conn) != 1) {
        return -1;
    }
    return 0;
}

int cmd_remove(MYSQL *conn, const char *username, const char *path){
    if(strlen(path)==1 && path[0]=='/'){
        return -1;
    }
    char new_path[PATH_SIZE];
    char filename[PATH_SIZE];
    split_path(path,new_path,filename);
    char sql[BUFFER_SIZE];
    snprintf(sql,sizeof(sql),"delete from user_files where user_id = (select id from user where username = '%s') and path = '%s' and filename = '%s'and type = 'f';",username,new_path,filename);
    if(mysql_query(conn,sql)!=0){
        return -1;
    }
    if (mysql_affected_rows(conn) != 1) {
        return -1;
    }
    return 0;
}

